/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * StalkerLogin.java
 *
 * Created on 24/05/2011, 16:33:17
 */
package stalker;

import com.sun.java.swing.plaf.windows.resources.windows;
import java.awt.ComponentOrientation;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import shared.ClientEntity;

/**
 *
 * @author pemachado
 */
public class StalkerLogin extends javax.swing.JFrame {

    private static String DefaultDNSip;
    private static int DefaultDNSport;
    private Mensagem MsgToServer = new Mensagem(); 
    private Mensagem MsgfromClient = new Mensagem();
    private byte[] ByteBuffer;
    private SingleFrameApplication APP; //para abrir o FRAMEVIEW
    /** Creates new form StalkerLogin */    
    public StalkerLogin(SingleFrameApplication app) throws FileNotFoundException, IOException, Exception {
        APP = app;
        initComponents();

        //le arquivo.ini
        String FileName = "stalker.ini";
        boolean fileexists = (new File(FileName)).exists();
        if (fileexists) {
            InputStream is = new FileInputStream(FileName);
            Scanner entrada = new Scanner(is);
            String str;

            while (entrada.hasNextLine()) {
                str = entrada.nextLine().trim();
                if (str.contains("IP")) {
                    DefaultDNSip = str.substring(str.indexOf("=") + 1, str.length());//.replace(".","");
                } else if (str.contains("PORTA")) {
                    DefaultDNSport = Integer.parseInt(str.substring(str.indexOf("=") + 1, str.length()));
                }
            }
            is.close();
        } else {
            throw new Exception("Arquivo.ini nao encontrado no diretorio raiz");
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        txtNome = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtPorta = new javax.swing.JTextField();
        btnConectar1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        lblmensagem = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(stalker.StalkerApp.class).getContext().getResourceMap(StalkerLogin.class);
        txtNome.setText(resourceMap.getString("txtNome.text")); // NOI18N
        txtNome.setName("txtNome"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        txtPorta.setText(resourceMap.getString("txtPorta.text")); // NOI18N
        txtPorta.setName("txtPorta"); // NOI18N

        btnConectar1.setText(resourceMap.getString("btnConectar1.text")); // NOI18N
        btnConectar1.setName("btnConectar1"); // NOI18N
        btnConectar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConectar1ActionPerformed(evt);
            }
        });

        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setForeground(resourceMap.getColor("jLabel3.foreground")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        lblmensagem.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblmensagem.setText(resourceMap.getString("lblmensagem.text")); // NOI18N
        lblmensagem.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        lblmensagem.setName("lblmensagem"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtPorta, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(36, 36, 36)
                        .addComponent(btnConectar1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(122, 122, 122)
                        .addComponent(jLabel3))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblmensagem, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(41, 41, 41)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txtPorta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(btnConectar1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addComponent(lblmensagem)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnConectar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConectar1ActionPerformed
        try {
            
            if (txtNome.getText().trim().equals("")) {                
                JOptionPane.showMessageDialog(this,"Favor preencha o nick.","Erro",JOptionPane.ERROR_MESSAGE);
                return;
            }else if (txtNome.getText().trim().contains(" ")) {                
                JOptionPane.showMessageDialog(this,"Nick não pode ter espaços vazios.","Erro",JOptionPane.ERROR_MESSAGE);
                return;
            }else if (txtPorta.getText().trim().equals("")) {
                JOptionPane.showMessageDialog(this,"Favor preencha a porta.","Erro",JOptionPane.ERROR_MESSAGE);
                return;
            }

            // verificar se apenas passando a String do host o
            // socket consegue resolver o nome o se precisamos de
            // InetAddress IPAddress = InetAddress.getByName(args[0]);
            // e passar o objeto da classe InetAddress... 
            Socket sock = new Socket(DefaultDNSip, DefaultDNSport); // cria socket
            

            // pega os fluxos out e in do socket TCP e encapusla em
            // ... fluxos de objeto
            ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(sock.getInputStream());

            
            // cria a estrutura de dados a ser enviada
            MsgToServer = new Mensagem();
            MsgToServer.setCdTransacao((byte)1);
            MsgToServer.setIp(MsgToServer.ipToInt(InetAddress.getLocalHost().getHostAddress()));
            MsgToServer.setPorta(Short.parseShort(txtPorta.getText()));
            MsgToServer.setTexto(txtNome.getText());
            
            out.write(MsgToServer.convertToByteBuffer());
            out.flush();
            
            
            ByteBuffer = new byte[1024];
            in.read(ByteBuffer);  
            
            MsgfromClient.convertToClass(ByteBuffer);
            
            if (MsgfromClient.getTexto().startsWith("OK"))
                //abre janela de conversa
                APP.show(new StalkerView(APP, DefaultDNSip, DefaultDNSport, txtNome.getText(), Short.parseShort(txtPorta.getText())));           
            else
                lblmensagem.setText(MsgfromClient.getTexto());
           
            in.close();
            out.close();
            sock.close(); // fecha socket

            this.setVisible(false);

        } catch (Exception ex) {
            lblmensagem.setText(ex.getMessage());
        }
}//GEN-LAST:event_btnConectar1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConectar1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel lblmensagem;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtPorta;
    // End of variables declaration//GEN-END:variables
}
